package com.kaibes.module.token;

import java.math.BigInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.module.token.core.TokenUtils;
import com.kaibes.module.token.pojo.Token;
import com.kaibes.module.token.service.TokenService;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.api.ResponseApi;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/tokens")
public class TokenApi extends ResponseApi<Token, TokenService> {

    @Autowired
    private TokenService tokenService;

    @DeleteMapping("/{id:\\d+}")
    @ApiLink("删除token")
    public ResponseEntity<Object> delete(@PathVariable BigInteger id) {
        return ResponseFactory.delete(service.removeById(id), "删除成功", "删除失败");
    }

    @DeleteMapping("/logout")
    @ApiLink(value = "用户登出", validated = false)
    public ResponseEntity<Object> delete(@RequestAttribute Token token, HttpServletRequest request, HttpServletResponse response) {
        tokenService.removeByUserIdAndType(token.getUserId(), token.getType());
        TokenUtils.deleteTokenFromCookie(request, response);
        return ResponseFactory.postSuccess("您已退出登录");
    }

}
